#include "stdafx.h"
#include "Event.hpp"


HpsFramework::Threading::Event::Event() : _created(true)
{
	this->_event = CreateEvent ( NULL, FALSE, FALSE, NULL );
	if(!this->_event)
	{
		this->_created = false;
	}
}

HpsFramework::Threading::Event::~Event()
{
	if(this->_created)
	{
		CloseHandle(this->_event);
	}
}

HANDLE HpsFramework::Threading::Event::getEvent()
{
	return this->_event;
}

bool HpsFramework::Threading::Event::created()
{
	return this->_created;
}

void HpsFramework::Threading::Event::set()
{
	if(this->_created)
		SetEvent(this->_event);
}

bool HpsFramework::Threading::Event::wait( unsigned int ms /*= INFINITE */ )
{
	if(WaitForSingleObject(this->_event, ms) != WAIT_OBJECT_0)
	{
		return false;
	}
	return true;
}

void HpsFramework::Threading::Event::reset()
{
	if(this->_created)
		ResetEvent(this->_event);
}

//------------------------------------------------------------------------------------------------

HpsFramework::Threading::WsaEvent::WsaEvent() 
	: _created(true)
{
	this->_event = WSACreateEvent();
	if(!this->_event)
	{
		this->_created = false;
	}
}

HpsFramework::Threading::WsaEvent::~WsaEvent()
{
	if(this->_created)
	{
		WSACloseEvent(this->_event);
	}
}

HANDLE HpsFramework::Threading::WsaEvent::getEvent()
{
	return this->_event;
}

bool HpsFramework::Threading::WsaEvent::created()
{
	return this->_created;
}

bool HpsFramework::Threading::WsaEvent::wait( unsigned int ms /*= INFINITE */ )
{
	if(WSAWaitForMultipleEvents (1, &this->_event, FALSE, ms, FALSE) == WSA_WAIT_TIMEOUT)
	{
		return false;
	}
	return true;
}

int HpsFramework::Threading::WsaEvent::select( SOCKET s, long events )
{
	return ::WSAEventSelect ( s, this->_event, events);
}
